<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="代理商名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入代理商名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="leader">
        <el-input
          v-model="queryParams.leader"
          placeholder="请输入负责人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="代理商状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:acting:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="actingList"
      row-key="id"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="代理商名称" align="center"></el-table-column>
      <el-table-column prop="leader" label="负责人" align="center"></el-table-column>
      <el-table-column prop="phone" label="代理商手机号码" align="center"></el-table-column>
      <el-table-column prop="orderNum" label="排序" align="center"></el-table-column>
      <el-table-column prop="email" label="代理商邮箱" align="center"></el-table-column>
      <el-table-column prop="videoCount" label="视频数量" align="center"></el-table-column>
      <el-table-column prop="usableBalance" label="可提现余额" align="center"></el-table-column>
      <el-table-column prop="freezeBalance" label="冻结余额" align="center"></el-table-column>
      <el-table-column prop="totalBalance" label="总余额" align="center"></el-table-column>
      <el-table-column  label="代理商状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="changeStatus($event,scope.row.id)"
            active-text="开"
            inactive-text="关"
            active-color="#3894ff"
            v-has-permi="['system:proxy:edit']"
            inactive-color="#ed5565">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:proxy:list:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:proxy:add']"
          >新增</el-button>
          <el-button
            v-if="rolesKey == '00'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['system:admin:addVideoCount']"
            @click="handleRecharge(scope.row,0)"
          >充值</el-button>
          <el-button
            v-if="rolesKey == '01'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['order:order:createOrder']"
            @click="handleRecharge(scope.row,1)"
          >充值次数</el-button>

          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:proxy:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleCollocation(scope.row)"
            v-hasPermi="['system:branch:config:edit']"
          >配置</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleCollocationDetail(scope.row)"
            v-hasPermi="['system:branch:config:query']"
          >配置详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改代理商对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商家头像" prop="parentId" v-if="ifAdd == 1">
              <upload v-model="form.pic" :limit="1" @uploadSuccess="uploadSuccess"></upload>
<!--              <el-upload-->
<!--                class="avatar-uploader"-->
<!--                action="url"-->
<!--                :show-file-list="false"-->
<!--                :on-success="handleAvatarSuccess"-->
<!--                :before-upload="beforeAvatarUpload">-->
<!--                <img v-if="imageUrl" :src="imageUrl" class="avatar">-->
<!--                <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--              </el-upload>-->

            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级代理商" prop="parentId">
              <treeselect v-model="form.parentId"  :options="actingOptions" label="name"  :normalizer="normalizer" placeholder="选择上级代理商"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理商名称" prop="name" label-width="100px">
              <el-input v-model="form.name" placeholder="请输入代理商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理商状态" label-width="100px">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    充值-->
    <el-dialog
      title="充值"
      :visible.sync="rechargeOpen"
      width="30%"
      :before-close="rechargeClose">
      <span style="display:block;margin-bottom: 20px;">{{rechargeTitle}}</span>
      <el-form :model="rechargeQuery"
               ref="recharge"
               :rules="rules"
               @submit.native.prevent
               class="demo-ruleForm">
        <el-form-item
          prop="videoCount"
        >
          <el-input v-model.number="rechargeQuery.videoCount"
                    @keyup.enter.native="recharge"
                    placeholder="请输入充值数量"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rechargeClose">取 消</el-button>
        <el-button type="primary" @click="recharge">确 定</el-button>
      </div>
    </el-dialog>
    <!--修改配置弹出框-->
    <el-dialog
      title="代理商配置信息"
      :visible.sync="collocationOpen"
    >
      <el-form :model="collocationForm" :rules="rules" label-width="130px">
        <el-form-item label="一级返利比例" prop="oneProxyRatio">
          <el-input v-model="collocationForm.oneProxyRatio"/>
        </el-form-item>
        <el-form-item label="代理商pc充值单价" prop="proxyPrice">
          <el-input v-model="collocationForm.proxyPrice"/>
        </el-form-item>
        <el-form-item label="二级返利比例" prop="towProxyRatio">
          <el-input v-model="collocationForm.towProxyRatio"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCollocation">确 定</el-button>
        <el-button @click="cancelCollocation">取 消</el-button>
      </div>
    </el-dialog>
    <!--查看配置详情弹出框-->
    <el-dialog
      title="详情"
      :visible.sync="collocationDetail"
      @close="cancelCollocationDetail"
      width="50%"
    >
      <el-descriptions :column="2" :colon="false">
        <el-descriptions-item><span style="font-size: 15px; color:#1890ff">id :</span>&emsp;{{collocationForm.id}}</el-descriptions-item>
        <el-descriptions-item><span style="font-size: 15px; color:#1890ff">一级返利比例 :</span>&nbsp;{{collocationForm.oneProxyRatio}}</el-descriptions-item>
        <el-descriptions-item><span style="font-size: 15px; color:#1890ff">代理商pc充值单价 :</span>&nbsp;{{collocationForm.proxyPrice}}</el-descriptions-item>
        <el-descriptions-item><span style="font-size: 15px; color:#1890ff">二级返利比例 :</span>&nbsp;{{collocationForm.towProxyRatio}}</el-descriptions-item>
        <el-descriptions-item><span style="font-size: 15px; color:#1890ff">更新时间 :</span>&nbsp;{{collocationForm.updateTime}}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <!--打开支付码-->
    <div class="code__dialog">
      <el-dialog
        title="请用打开微信扫码"
        :visible.sync="codeOpen"
        @close="cancelCode"
        width="13%"

      >
        <div class="lookCode">
          <div id="qrCode" ref="payCode"></div>
          <div class="refresh__code" @click="recharge" v-if="showRefreshCode">
            <i class="el-icon-refresh-right"></i>
            <span>请刷新</span>
          </div>
        </div>
      </el-dialog>

    </div>

  </div>
</template>

<script>
import {
  listActing,
  getActing,
  delActing,
  addActing,
  updateActing,
  listActingExcludeChild,
  proxyUserCount,
  actingStatus,
  getProxyVideoCount,
  getCollocation,
  editCollocation,
  createOrder,
  getPayStatus
} from '@/api/acting/acting'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listDeptExcludeChild } from '@/api/system/dept'
import { addVideCount, transferVideoCount } from '@/api/acting/user'
import { mapState } from 'vuex';
import QRCode from 'qrcodejs2';
import upload from '@/components/ImageUpload'
import{getCardDetail} from "@/api/acting/card";
export default {
  name: "Dept",
  components: { Treeselect,upload },
  data() {
    const numberRule = (rule, value, callback) => {
      if (Number(value) < this.rechargeMax) {

        if (Number.isInteger(Number(value)) && Number(value) > 0) {
          callback()
        } else {
          callback(new Error('请输入大于零的正整数'))
        }
      } else {
        callback(new Error('次数不能大于'+this.rechargeMax +'次'))
      }
    }
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      imageUrl: '',
      // 表格树数据
      actingList:[

      ],

      // 代理商树选项
      actingOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      //新增修改时头像是否显示
      ifAdd: 1,
      // 查询参数
      queryParams: {
        actingName: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        pic: undefined,
      },
      //充值参数
      rechargeQuery:{
        type:0 //0代理商 1商户
      },
      // 上传的地址
      url: process.env.VUE_APP_BASE_URL + "/system/user/importData",
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级代理商不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "代理商名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        leader: [
            {
              min: 2,
              message: "不能少于两个字符",
              trigger: "change"
            }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        videoCount: [
          { required: true, message: '充值次数不能为空' },
          { type: 'number', message: '必须为数字值' },
          { validator: numberRule, trigger: ['change','blur'] }
        ],
      },
      //最大充值数量
      rechargeMax:99,
      //充值内容
      rechargeTitle: '',
      rechargeOpen: false,
      //配置表单
      collocationForm: {},
      //是否打开修改配置弹窗
      collocationOpen: false,
      //是否打开配置详情
      collocationDetail: false,
      //是否打开银行卡详情
      cardDetailOpen: false,
      //充值二维码弹窗
      codeOpen:false,
      //刷新时间
      checkTime:0,
      //刷新时长
      maxTime:30,
      //当二维码过期时显示刷新按钮
      showRefreshCode:false,
    };
  },
  computed: {
    ...mapState({
      rolesKey: state => state.user.rolesKey
    })
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
      this.statusOptions.forEach(item =>{
        item.dictValue = Number(item.dictValue)
      })
    });
  },
  mounted() {


  },

  methods: {
    /** 查询代理商列表 */
    getList() {
      this.loading = true;
      listActing(this.queryParams).then(response => {
        this.actingList= response.data;
        this.loading = false;
      });
    },
    //充值操作 type 0超级管理员充值 1是代理商充值
    handleRecharge(row,type) {
      this.rechargeOpen = true
      this.rechargeQuery.publicId = row.id
      if (type == 0){
        getProxyVideoCount().then(res =>{
          this.rechargeMax = res.data;
          this.rechargeTitle = '请输入给商户"' + row.name + '"充值的视频数量。最大充值数量为'+res.data+'次'
        })
      }else {
        this.rechargeTitle = '请输入充值数量'
      }
    },
    //充值取消操作
    rechargeClose() {
      this.rechargeOpen = false
      this.rechargeTitle = '';

      this.rechargeQuery = {
        type: 0
      }
      this.resetForm('recharge')
    },
    //充值
    recharge() {

      this.$refs['recharge'].validate(valid => {
        if (valid) {
          if (this.rolesKey == '01'){
            this.showRefreshCode = false;
            const loading = this.$loading({
              lock: true,
              text: '正在生成订单，请稍后',
              spinner: 'el-icon-loading',
            });
            createOrder({
              videoCount:this.rechargeQuery.videoCount,
              proxyId:this.rechargeQuery.publicId
            }).then(res =>{
              this.codeOpen = true;
              loading.close()
              let timer = setInterval(() => {
                this.checkStatus(timer,res.data.orderNum);
              }, 1000)
              this.$nextTick(function () {
                this.bindQRCode(res.data.url);
              })
            }).catch(err =>{
              loading.close()
            })
          }
          if (this.rolesKey == '00'){
            addVideCount(this.rechargeQuery).then(res =>{
              this.msgSuccess("充值成功");
              this.getList();
              this.rechargeClose();
            })
          }

        }
      })
    },
    //检查支付是否成功
    checkStatus(timer,orderNum) {
      const _this = this;
      setTimeout(() => {
        getPayStatus(orderNum).then(res => {
          if (!res.data) {
            _this.checkTime += 1;
            if (_this.checkTime == _this.maxTime) {
              clearInterval(timer);
              _this.checkTime = 0;
              _this.showRefreshCode = true;

            }
          } else {
            _this.cancelCode();
            _this.rechargeClose();
            _this.getList();

            _this.$message.success("支付成功")
            clearInterval(timer);
          }


        }).catch(err =>{
          clearInterval(timer);
        })


      }, 0)
    },
    //二维码函数
    bindQRCode: function (url) {
      new QRCode(this.$refs.payCode, {
        text: url,
        width: 200,
        render: "canvas",
        height: 200,
        colorDark: "#333333", //二维码颜色
        colorLight: "#ffffff", //二维码背景色
        correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
      })
    },
    uploadSuccess(url){
      this.form.pic = url

    },

    /** 转换代理商数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        actingName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0"
      };
      this.getList()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {

      this.reset();
      this.ifAdd = 1;
      if (row != undefined) {
        this.form.parentId = row.id;
      }

      this.open = true;
      this.title = "添加代理商";
      listActing().then(response => {
        this.actingOptions = response.data;
        // console.log(this.actingOptions)
      });
      this.form.status =0
      // console.log(this.form)
    },
    /** 修改代理商状态 */
    changeStatus(e,id){
      actingStatus({
        proxyId:id,
        status:e
      }).then(res =>{
        if (res.code == 200){
          if (e == 0){
            this.msgSuccess('已开启代理商')

          }else {
            this.msgInfo('已关闭代理商')

          }

        }else {
          this.msgSuccess('操作，请联系管理员')
          this.getList();

        }

      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.ifAdd = 0;
      getActing(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改代理商";
      });
      listActingExcludeChild(row.id).then(response => {
        this.deptOptions = response.data;
      });

    },
    /**配置按钮 */
    handleCollocation(row) {
      console.log(row)
      let id = row.id;
       getCollocation(id).then(response => {
        this.collocationForm = response.data
        this.collocationOpen = true;
      });
    },
    /**配置详情 */
    handleCollocationDetail(row) {
      getCollocation(row.id).then(response => {
        this.collocationForm = response.data;
        this.collocationDetail = true;
      });
    },

    /**取消配置按钮 */
    cancelCollocation() {
      this.collocationOpen = false
      this.collocationForm = {};
    },

    /**退出配置详情 */
    cancelCollocationDetail() {
      this.collocationDetail = false
      this.collocationForm = {};

    },
    /**关闭二维码弹窗 */
    cancelCode(){
      this.codeOpen = false
      this.$refs.payCode.innerHTML = '';
    },

    /**提交配置按钮 */
    submitCollocation() {
      editCollocation(this.collocationForm).then(response => {
              this.msgSuccess("修改成功");
              this.collocationOpen = false;
              this.getList();
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateActing(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActing(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const _this =  this;
      this.$confirm('是否确认删除代理商"' + row.name + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        proxyUserCount(row.id).then(res =>{
          console.log(res)
          if (res.data == 0){

             delActing(row.id,false).then(res =>{
               _this.getList();
               _this.msgSuccess("删除成功");
             });

          }else{
            _this.$confirm('您是否愿意把你的用用户给上一级代理继承', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {


               delActing(row.id,true).then(res =>{
                 _this.getList();
                 _this.msgSuccess("删除成功");
               });

            });
          }

        })


      }).then(() => {

      }).catch(() => {});
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  ::v-deep .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  ::v-deep .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .code__dialog ::v-deep .el-dialog__body{
    display: flex;
    justify-content: center;
  }
  .lookCode{
    display: flex;
    flex-flow: column;
    align-items: center;
    position: relative;
    width: 200px;
    height: 200px;
    overflow: hidden;
    .refresh__code {
      position: absolute;
      top: 0;
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.8);
      display: flex;
      flex-flow: column;
      justify-content: center;
      align-items: center;
      z-index: 99;
      >i{
        font-size: 30px;
        color: #ffffff;
        cursor: pointer;
      }

      >span {
        color: #ffffff;
        margin-top: 20px;
      }
    }
    #qrCode{
      width: 200px;
    }
  }
</style>
